import React from 'react';
import { Modal, Form, Input, message } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import { formItemLayout } from '../common';
import RecordUpload from './recordUpload';
import { getLocation } from '../../utils/index';
import ImageUpload from './ImageUpload';

const FormItem = Form.Item;
const mainPorps = ['id', 'distributeNumber', 'doneNumber', 'last_dst_time'];
const defaultFormItems = [
  {
    label: '文本行',
    id: 'lineNumber',
    rules: [
      {
        required: true,
        message: '文本行不能为空',
      },
    ],
    component: <Input placeholder="请输入文本行" type="number" />,
  },
  {
    label: '文本',
    id: 'text',
    rules: [
      {
        required: true,
        message: '文本不能为空',
      },
    ],
    component: <Input placeholder="请输入文本" />,
  },
  {
    label: '音频',
    id: 'audio',
    component: (<RecordUpload />),
  },
  {
    label: '图片',
    id: 'image',
    component: (<ImageUpload />),
  },
];


const map = {
  create: {
    title: '新建条目',
    button: '新建',
    effect: 'record/createRecord',
    success: '创建条目成功',
  },
  edit: {
    title: '更新条目',
    button: '更新',
    effect: 'record/editRecord',
    success: '更新条目成功',
  },
};

class RecordModal extends React.Component {

  constructor(p) {
    super(p);
    this.handleOk = this.handleOk.bind(this);
    this.state = {
      formItems: _.cloneDeep(defaultFormItems),
    };
    const { type, data } = this.props;
    // edit 模式下填入默认数据
    if (type === 'edit') {
      const formItems = _.cloneDeep(defaultFormItems);
      Object.keys(data).forEach((key) => {
        // 过滤掉一些不能更改的数据
        if (mainPorps.indexOf(key) >= 0) {
          return;
        }
        const index = _.findIndex(formItems, (item) => {
          return item.id === key;
        });
        if (index >= 0) {
          formItems[index].initialValue = data[key];
        } else if (typeof data[key] === 'string' || typeof data[key] === 'number') {
          formItems.push({
            label: key,
            id: key,
            component: <Input placeholder={`请输入${key}`} />,
            initialValue: data[key],
          });
        }
      });
      this.state.formItems = formItems;
    }
  }

  handleOk() {
    const {
      validateFields,
      getFieldsValue,
    } = this.props.form;
    const { dispatch, onFinish, type, data } = this.props;
    validateFields((err) => {
      if (!err) {
        const value = getFieldsValue();
        // 补全id
        if (type === 'edit') {
          value.id = data.id;
        }
        const location = getLocation();
        const taskId = _.get(location, 'query.taskId');
        if (!taskId) {
          return message.error('缺少任务id,请回到主页面重新开始');
        }
        value.task = taskId;
        // if (typeof value.audio !== 'string') {
        //   return message.error('音频上传中或者上传失败，请重试');
        // }
        dispatch({
          type: map[type].effect,
          payload: {
            value,
            onEnd: (error) => {
              if (error) {
                return message.error(String(error.message || error));
              }
              message.success(map[type].success);
              onFinish();
            },
          },
        });
      }
    });
  }

  render() {
    const { visible, type, loading } = this.props;
    const {
      getFieldDecorator,
    } = this.props.form;
    return (
      <Modal
        visible={visible}
        okText={map[type].button}
        title={map[type].title}
        onOk={this.handleOk.bind(this)}
        onCancel={this.props.onFinish}
        confirmLoading={loading.effects[map[type].effect]}
      >
        <Form layout="horizontal">
          {
              this.state.formItems.map((item) => {
                return (
                  <FormItem key={item.id} label={item.label} hasFeedback {...formItemLayout}>
                    {
                      getFieldDecorator(
                        item.id, {
                          rules: item.rules,
                          initialValue: item.initialValue,
                        },
                      )(item.component)
                    }
                  </FormItem>
                );
              })
            }
        </Form>
      </Modal>
    );
  }
}

RecordModal.defualtProps = {
  visible: false,
  type: null,
  onFinish: () => null,
};

export default connect(state => state)(Form.create()(RecordModal));
